package com.crpc.core.serialize.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/29 15:16
 */
@Slf4j
public class HessianSerializer implements Serializer {
    public HessianSerializer() {
    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
            hessian2Output.writeObject(object);
            hessian2Output.flush();
            log.info("===============使用Hessian完成序列化===============");
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            log.error("序列化对象：{}，异常原因：{}", object, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null) {
            return null;
        }
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            Hessian2Input hessian2Input = new Hessian2Input(byteArrayInputStream);
            log.info("===============使用Hessian完成反序列化===============");
            return (T) hessian2Input.readObject();

        } catch (Exception e) {
            log.error("反序列化对象失败，字节：{}，失败原因：{}", bytes, e.getMessage());
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.Serialize_ERROR);
        }
    }
}
